package com.example.onion.hxchat.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;


import com.example.databean.FriendApplyBean;
import com.example.onion.hxchat.activity.InfoActivity;
import com.example.onion.hxchat.mvvm.WcFriendViewModel;
import com.example.onion.hxchat.room.entity.Friend;
import com.example.onion.hxchat.util.MyLocalDatabaseHelper;
import com.example.onion.hxchat.util.PassWordHelp;
import com.example.superyi.mainBar.MainBar;
import com.example.superyi.myteam.R;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;

import java.util.List;
/**
 * 适配器，你们应该不用用到我的适配器不多写了吧
 * 等待获取到用户名userName，修改传递的参数 98
 * 含version
 * 涉及处理好友申请，保存等操作
 */
public class MyNotificationAdapter extends RecyclerView.Adapter<MyNotificationAdapter.ViewHolder> {

    List<FriendApplyBean> mList;
    Context mContext;
    private applyResultListener mApplyResultListener;

    private String accountId;
    private int version = 4;

    private WcFriendViewModel friendViewModel;
    public MyNotificationAdapter() {
    }

    public MyNotificationAdapter(List<FriendApplyBean> mList, Context mContext,WcFriendViewModel friendViewModel) {
        this.mList = mList;
        this.mContext = mContext;
        this.friendViewModel = friendViewModel;
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        ImageView userImg;
        TextView nameText;
        TextView contentText;
        Button acceptApply;
        Button rejectApply;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            userImg = itemView.findViewById(R.id.notification_user_img_iv_wc);
            nameText = itemView.findViewById(R.id.notification_user_name_tv_wc);
            contentText = itemView.findViewById(R.id.notification_content_tv_wc);
            acceptApply = itemView.findViewById(R.id.notification_accept_apply_btn_wc);
            rejectApply = itemView.findViewById(R.id.notification_reject_apply_btn_wc);
        }
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.notification_item, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        FriendApplyBean friendApplyBean = mList.get(position);
        String userId = friendApplyBean.getUserId();
        holder.nameText.setText(friendApplyBean.getUserName());
        holder.contentText.setText(friendApplyBean.getApplyContent());
        holder.userImg.setImageResource(friendApplyBean.getUserImg());

        holder.rejectApply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mApplyResultListener.rejecttApply(friendApplyBean);
                    deleteNotification(userId);
                    Intent intent = new Intent(mContext, MainBar.class);
                    mContext.startActivity(intent);
                } catch (HyphenateException e) {
                    Toast.makeText(mContext,"unknown error!",Toast.LENGTH_SHORT);
                    e.printStackTrace();
                }
            }
        });
        holder.acceptApply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mApplyResultListener.acceptApply(friendApplyBean);
                    deleteNotification(userId);
                    Intent intent = new Intent(mContext, MainBar.class);
                    mContext.startActivity(intent);
                } catch (HyphenateException e) {
                    Toast.makeText(mContext,"unknown error!",Toast.LENGTH_SHORT);
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 判断是否已经存在好友关系
     * @param userId id
     * @return 已经保存好友关系返回true,否则false
     */
    private boolean isExistFriend(String userId){
        MyLocalDatabaseHelper dbHelper = new MyLocalDatabaseHelper(mContext,"local.db",null,version);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select userId from friend where userId = ?",new String[]{userId});
        if(cursor.moveToFirst()){
            return true;
        }
        return false;
    }

    /**
     * 保存与userId的好友关系
     * @param userId id
     * @param userName 昵称
     */
    @SuppressLint("LongLogTag")
    private void storeFriend(String userId, String userName)
    {
        accountId = PassWordHelp.readPassword(mContext)[0];
        Log.e("NotificationAdapter accountId",accountId);
        Friend friend = new Friend(userName,userId,accountId);
        friendViewModel.insertFriend(friend);
//        MyLocalDatabaseHelper dbHelper = new MyLocalDatabaseHelper(mContext,"local.db",null,version);
//        SQLiteDatabase db = dbHelper.getWritableDatabase();
//        db.execSQL("insert into friend(userId,userName) values(?,?)",new String[]{userId,userName});

    }


    /**
     * 答复完毕后删除相关好友请求通知
     * @param userId
     */
    private void deleteNotification(String userId)
    {
        MyLocalDatabaseHelper dbHelper = new MyLocalDatabaseHelper(mContext,"local.db",null,version);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.execSQL("delete from notification where userId = ?",new String[]{userId});
    }
    @Override
    public int getItemCount() {
        return mList.size();
    }


    public interface applyResultListener {//适配器内创建一个回调接口，获取每一行recyclerview的相关数据

        void acceptApply(FriendApplyBean friendApplyBean) throws HyphenateException;//用户接收（notificationBean的userId)的好友请求

        void rejecttApply(FriendApplyBean friendApplyBean) throws HyphenateException;//用户拒绝（notificationBean的userId)的好友请求
    }

    public void setApplyResultListener(applyResultListener applyResultListener) {
        this.mApplyResultListener = applyResultListener;
    }

}
